<template>
	<!-- 活动列表 -->
	<view class="store-list" :style="'padding-top : ' + navigationBarTop ">
		<img class="bg-img" src="@appstatic/img/my/bg-img.jpg" alt="">
		<!-- #ifndef MP-WEIXIN -->
		<u-navbar title="派方之家" @rightClick="rightClick" bgColor='#f5f5f5' :autoBack="true">
			<view class="navbar-icon" slot='right'>
				<image class="icon-img" :src="ossUrl + 'car-store-icon-headermap.png'" mode="widthFix" />
				{{city ? city : province || '选择省市'}}
				<view :class="showPicker ? 'arrow open': 'arrow '"></view>
			</view>
		</u-navbar>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<u-navbar title="派方之家"   bgColor='#f5f5f5' :autoBack="false">
			<view class="navbar-icon" slot='left'>
				<u-icon name="arrow-left" size="20px" color="#303133" @click="autoBack"></u-icon>
				<view @click="rightClick" style="padding-left: 5px;">
					<image class="icon-img" :src="ossUrl + 'car-store-icon-headermap.png'" mode="widthFix" />
					{{city ? city : province || '选择省市'}}
					<view :class="showPicker ? 'arrow open': 'arrow '"></view>
				</view>
			</view>
		</u-navbar>
		<!-- #endif -->

		<z-paging ref="paging" v-model="storeList" refresher-refreshing-text="  " @query="queryList"
			@onRefresh='onRefresh' :height='"calc(100vh - " + navigationBarTop + ")"' :fixed="false" :auto="false">
			<view :class="topLoading ? 'top-box ' : 'top-box z-index'" slot='top'>
				<view class="tabs-box">
					<!-- open -->
					<view
						:class="(current.sortFlag ? 'tab-items currnet ': 'tab-items ') + (currentTabs == 'sortFlag' ? 'open': '')"
						>{{current.sortFlag ? current.sortFlag: '排序'}}
						<view class="arrow"></view>
					</view>
					<view
						:class="(current.storeType ? 'tab-items currnet ': 'tab-items ') + (currentTabs == 'storeType' ? 'open': '')"
						@click="clickTabs('storeType')">{{current.storeType ? current.storeType: '门店类型'}}
						<view class="arrow"></view>
					</view>
					<view
						:class="(current.businessArea ? 'tab-items currnet ': 'tab-items ') + (currentTabs == 'businessArea' ? 'open': '')"
						@click="clickTabs('businessArea')">{{current.businessArea ? current.businessArea: '经营范围'}}
						<view class="arrow"></view>
					</view>
				</view>
			</view>
			<view class="popups" mode="top" v-if="show" zIndex='10081' :safeAreaInsetBottom="false">
				<view class="pop-con">
					<view :class="currentTabs == 'businessArea' ? 'select-item select-item3': 'select-item '">
						<view :class="item.selected ? 'item selected': 'item'" v-if='currentTabs == "sortFlag"'
							v-for='item, index in selectList.sortFlag' :key='index'
							@click="selectedItems('sortFlag', index, item.uuid)">{{item.contentName}}</view>
						<view :class="item.selected ? 'item selected': 'item'" v-if='currentTabs == "storeType"'
							v-for='item, index in selectList.storeType' :key='index'
							@click="selectedItems('storeType', index, item.uuid)">{{item.contentName}}</view>
						<view :class="item.selected ? 'item selected': 'item'" v-if='currentTabs == "businessArea"'
							v-for='item, index in selectList.businessArea' :key='index'
							@click="selectedItems('businessArea', index, item.uuid)">{{item.contentName}}</view>
					</view>
				</view>
			</view>
			<view class="card-list">
				<view class="items" v-for='item, index in storeList' :key='index'>
					<view class="img-box">
						<image class="store-img"
							:src="item.levcDataStore.storeImageMobile ? item.levcDataStore.storeImageMobile : (ossUrl + 'car-store-content-nophoto.png')"
							mode="aspectFill" />
						<view class="store-type">{{item.levcDataStore.typeFlag}}</view>
					</view>
					<view class="text-box">
						<view class="store-name">{{item.levcDataStore.storeName}}</view>
						<view class="store-label" v-for='ite,inde in (item.levcDataStore.businessArea.split(","))'>
							{{ite}}
						</view>
						<view class="store-address">
							<image :src="ossUrl + 'car-store-icon-conmap.png'" mode="widthFix" />
							{{item.levcDataStore.storeAddress}}
						</view>
						<view class="store-address store-km">{{item.distance.toFixed(2)}}km</view>
						<view class="btn-box">
							<view class="map-btn"
								@click='showMapModal(item.latitude, item.longitude, item.levcDataStore.storeAddress)'>
								<image :src="ossUrl + 'car-store-icon-address.png'" mode="widthFix" /> 导航前往
							</view>
							<!-- <view class="phone-btn" @click="callPhone(item.levcDataStore.storePhone)"> <image :src="ossUrl + 'car-store-icon-phone.png'" mode="widthFix"/> 电话联系</view> -->
							<view class="phone-btn" @click="selectPhone(item.levcDataStore)">
								<image :src="ossUrl + 'car-store-icon-phone.png'" mode="widthFix" /> 电话联系
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- <empty v-if='!storeList.length && refreshEnd' text='暂无任何数据' /> -->
			<!-- <view v-if="pageEnd && storeList.length" class="end">全部加载完毕</view> -->
		</z-paging>
		<!-- 地址选择 -->
		<u-picker :show="showPicker" :columns="pickerColumns" keyName="label" confirmColor='#EA5404'
			@change="changeHandler" @cancel='pickerCancel' @confirm='pickerConfirm'></u-picker>
		<!-- 打电话 -->
		<u-modal :show="showPhone" :title='phone' confirmText='拨打' confirmColor='#EA5404' :showCancelButton='true'
			cancelColor='#3D3A3A' @confirm="confirmPhone" @cancel="canclePhone"></u-modal>
		<!-- 地图 -->
		<u-modal :show="showMap" title='地图选择' confirmText='确认' confirmColor='#EA5404' :showCancelButton='true'
			cancelColor='#3D3A3A' @confirm="confirmMap" @cancel="cancleMap" width="600rpx">
			<view class="slot-content confirmdialog-content">
				<view class="content-item" v-for='item, index in selectMapList' :key='index'  
					@click='selectMap(item.type, item.phone)'>{{item.name}}
					<u-icon v-if='currentMap == item.type' name="checkbox-mark" color="#EA5404" size="18"></u-icon>
				</view>
			</view>
		</u-modal>
	</view>

</template>

<script>
	const app = getApp();
	const network = require('@manager/network-manager.js');
	const dialog = require('@utils/dialog.js');
	import map from "../../../utils/qqmap-wx-jssdk.min.js"
	const mapUtils = require('@utils/mapUtils.js');
	import empty from '@components/empty/empty.vue'
	export default {
		components: {
			empty
		},
		data() {
			return {
				loadingEnd: false,
				ossUrl: '@appstatic/car/',
				show: false,
				showPicker: false,
				storeList: [],
				navigationBarTop: (app.globalData.statusBarHeight + 40) + 'px',
				current: {
					sortFlag: '距离排序',
					storeType: null,
					businessArea: null
				},
				currentTabs: null,
				selectList: {
					sortFlag: [
						// {
						// 	contentName: '默认排序',
						// 	selected: true,
						// 	uuid: '0'
						// },
						// {
						// 	contentName: '距离排序',
						// 	selected: false,
						// 	uuid: '1'
						// },
					],
					storeType: [],
					businessArea: [],
				},
				latitude: 0,
				longitude: 0,
				province: null,
				city: null,
				pickerColumns: [
					[],
					[]
				],
				topLoading: false,
				phone: null,
				showPhone: false,
				showMap: false,
				currentMap: null,
				currentMapPhone: null,
				selectMapList: [],
				currentLat: null,
				currentLong: null,
				currentAddress: null,
				params: {
					businessArea: '', // 经营范围
					storeType: '', // 门店类型
					sortFlag: '1', // 排序（0：默认 1：距离）
					province: '', // 省份
					city: '', // 城市
					latitude: '', // 纬度
					longitude: '', // 经度
				},
			}
		},
		onLoad() {
			//初始化位置北京
			// this.params.province="110000"
			// this.params.city="110100"
			// this.params.latitude="39.904172"
			// this.params.longitude="116.407417"
			// this.province="北京"
			// this.city="北京"
			// this.getList(1, 10, true)
			
			this.getProvinces()
			this.getStoreType()
			this.getBusinessArea()
		},
		onShow() {

		},
		mounted() {
			 
			this.getLocation()
			// this.checkCanUseMap()
			
			this.selectMapList = mapUtils.checkCanUseMap()
		},
		methods: {
			autoBack(){
				uni.navigateBack({
					delta: 1
				})
			},

			queryList(pageNo, pageSize) {
				debugger
				this.show = false
				this.getList(pageNo, pageSize)
			},

			onRefresh() {
				this.params.businessArea = ''
				this.params.storeType = ''
				this.params.sortFlag = '1'
				this.current = {
						sortFlag: '距离排序',
						storeType: null,
						businessArea: null
					},
					this.selectList.sortFlag.map(item => {
						item.selected = false
					})
				this.selectList.storeType.map(item => {
					item.selected = false
				})
				this.selectList.businessArea.map(item => {
					item.selected = false
				})
			},

			getList(pageNo, pageSize, flag) {
				debugger
				if (flag) this.storeList = []
				var url = app.globalData.config.interfaces.URL_GET_STORESLISTFORAPP
				var params = {
					...this.params,
					pageNum: pageNo,
					pageSize: pageSize
				};
				console.log(params)
				network.get(url, Object.assign({}, params), 'json', null, true).then(res => {
					if (res.code == 200) {
						// this.storeList = this.storeList.concat(res.data.list)
						this.$refs.paging.complete(res.data.list);
					}
				}).catch(err => {
					this.$refs.paging.complete(false);
					// this.$refs.paging.endRefresh()
				})
			},

			// 门店类型
			getStoreType() {
				var url = app.globalData.config.interfaces.URL_DICTIONARY_GETDICTIONARYLIST
				var params = {
					dictionaryCode: 'LEVC_STORE'
				};
				network.get(url, params, 'json').then(res => {
					if (res.code == 200) {
						res.data.map(item => {
							item.selected = false
						})
						this.selectList.storeType = res.data
					} else {
						uni.showToast({
							title: res.message,
							duration: 3000,
							icon: 'none'
						})
					}
				}).catch(res => {
					uni.showToast({
						title: res.errMsg,
						duration: 3000,
						icon: 'none'
					})
				});
			},

			// 经营范围
			getBusinessArea() {
				var url = app.globalData.config.interfaces.URL_DICTIONARY_GETDICTIONARYLIST
				var params = {
					dictionaryCode: 'LEVC_STORE_AREA'
				};
				network.get(url, params, 'json').then(res => {
					if (res.code == 200) {
						res.data.map(item => {
							item.selected = false
						})
						this.selectList.businessArea = res.data
					} else {
						uni.showToast({
							title: res.message,
							duration: 3000,
							icon: 'none'
						})
					}
				}).catch(res => {
					uni.showToast({
						title: res.errMsg,
						duration: 3000,
						icon: 'none'
					})
				});
			},

			//获取省
			async getProvinces() {
				var url = app.globalData.config.interfaces.URL_GET_PROVINCE
				var params = {
					"loginId": app.getUserId()
				}
				await network.get(url, params, 'form').then(res => {
					if (res.code == 200) {
						let arr = []
						res.data.ProvinceList.map(item => {
							item.label = item.provinceName, item.code = item.provinceCode, arr.push(
								item)
						})
						this.pickerColumns.splice(0, 1, arr)
						this.getCitys(this.pickerColumns[0][0]['provinceCode'])
					} else {
						uni.showToast({
							title: res.message,
							duration: 3000,
							icon: 'none'
						})
					}
				}).catch(res => {

				});
			},

			//获取市
			async getCitys(code) {
				var url = app.globalData.config.interfaces.URL_GET_CITY_BY_PROVINCE
				var params = {
					"loginId": app.getUserId(),
					"provinceCode": code
				}
				await network.get(url, params, 'form').then(res => {
					if (res.code == 200) {
						let arr = []
						res.data.cityList.map(item => {
							item.label = item.cityName, item.code = item.cityCode, arr.push(item)
						})
						this.pickerColumns.splice(1, 1, arr)
						this.loadingEnd = true
						// this.pickerColumns[1] = res.data.cityList
						// console.log('this.pickerColumns', this.pickerColumns)
					} else {
						uni.showToast({
							title: res.message,
							duration: 3000,
							icon: 'none'
						})
					}
				}).catch(res => {

				});
			},

			changeHandler(e) {
				const {
					columnIndex,
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				if (columnIndex === 0) {
					this.getCitys(this.pickerColumns[0][index]['provinceCode'])
				}
				// picker.setIndexs([1, 0])
			},

			pickerCancel() {
				this.showPicker = false
				setTimeout(() => {
					this.topLoading = false
				}, 500)
			},

			pickerConfirm(e) {
				console.log('e pickerConfirm', e)
				this.params.province = e.value[0].code
				this.params.city = e.value[1].code
				this.province = e.value[0].label
				this.city = e.value[1].label
				console.log('this.params', this.params)
				this.pickerCancel()
				this.getList(1, 10, true)
			},

			clickTabs(current) {
				if (current !== this.currentTabs) {
					this.show = true
				} else {
					this.show = !this.show
				}
				this.currentTabs = current
				if (!this.show) this.currentTabs = null
			},

			selectedItems(type, index) {
				// 当前是否有选择 
				if (this.current[type]) {
					// 有 判断是否是当前选择
					if (this.selectList[type][index]['selected']) {
						this.selectList[type][index]['selected'] = false
					} else {
						this.selectList[type].forEach(item => {
							item.selected = false
						})
						this.selectList[type][index]['selected'] = true
					}
				} else {
					this.selectList[type][index]['selected'] = true
				}
				this.current[type] = this.selectList[type][index]['selected'] ? this.selectList[type][index][
					'contentName'
				] : null
				this.params[type] = this.selectList[type][index]['selected'] ? this.selectList[type][index]['uuid'] : null
				if (this.params[type] == null) this.getList(1, 10, true)
				this.show = !Boolean(this.selectList[type].filter(item => {
					return item.selected == true
				}).length > 0)
				if (!this.show) this.currentTabs = null
				if (!this.show) this.getList(1, 10, true)

				console.log('this.params', this.params)
			},

			//获取地理位置
			getLocation() {
				let _this = this
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						console.log('获取地理位置', res.latitude+"++++"+res.longitude)
						_this.params.latitude = res.latitude
						_this.params.longitude = res.longitude
						var qqmapsdk = new map({
							key: 'SKABZ-LZZW5-VL7IR-IUYJA-L73D6-KMBO6' // 必填，去腾讯地图申请
						});
						qqmapsdk.reverseGeocoder({
							//Object格式
							location: {
								latitude: _this.params.latitude,
								longitude: _this.params.longitude
								// latitude: 41.872791,
								// longitude: 116.423088
							},
							success: (res) => {
								console.log('res reverseGeocoder', res)
								_this.params.province = res.result.ad_info.adcode.slice(0, 2) +
									'0000'
								_this.province = res.result.address_component.province
								_this.getList(1, 10, true)
							},
							fail: (error) => {
								_this.params.province = '110000'
								_this.params.city=  "110100"
								_this.params.latitude="39.904172"
								_this.params.longitude="116.407417"
								_this.province="北京"
								_this.city="北京"
								
								_this.getList(1, 10, true)
								
							}
						})
					},
					fail: (err) => {
						_this.params.province = '110000'
						_this.params.city=  "110100"
						_this.params.latitude="39.904172"
						_this.params.longitude="116.407417"
						_this.province="北京"
						_this.city="北京"
						
						
						
						_this.getList(1, 10, true)
					},
					complete() {

					}
				})


			},

			rightClick() {
				this.show = false
				this.showPicker = !this.showPicker
				this.topLoading = true
			},

			//选择电话
			selectPhone(levcDataStore) {
				var that = this
				var list = []
				if (levcDataStore.storePhone != null && levcDataStore.storePhone != '' && levcDataStore.storePhone !=
					undefined) {
					list.push('销售电话：' +
						levcDataStore.storePhone)
				}
				if (levcDataStore.afterSalesTel != null && levcDataStore.afterSalesTel != '' && levcDataStore
					.afterSalesTel != undefined) {
					list.push('售后电话：' +
						levcDataStore.afterSalesTel)
				}
				uni.showActionSheet({
					itemList: list,
					success: function(res) {
						that.callPhone(list[res.tapIndex].substring(5))
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});


			},




			//电话拨打
			callPhone(phone) {
				this.phone = phone
				this.showPhone = true
			},

			confirmPhone() {
				this.canclePhone()
				uni.makePhoneCall({
					phoneNumber: this.phone
				})
			},

			canclePhone() {
				this.topLoading = true
				this.showPhone = false
				setTimeout(() => {
					this.topLoading = false
				}, 500)
			},

			showMapModal(latitude, longitude, address) {
				this.currentMap = null
				//#ifndef MP-WEIXIN
				this.showMap = true
				//#endif
				this.currentLat = latitude
				this.currentLong = longitude
				this.currentAddress = address
				//#ifdef MP-WEIXIN
				mapUtils.openMapByDefault(this.currentLat, this.currentLong, this.currentAddress, this.currentMap)
				//#endif
			},

			confirmMap() {
				if (!this.currentMap) {
					uni.showToast({
						title: "请选择地图",
						icon: 'none',
						duration: 2000
					})
					return
				}
				if (this.currentMapPhone === 'Android') {
					mapUtils.openMapByAndroid(this.currentLat, this.currentLong, this.currentAddress, this.currentMap)
				} else {
					mapUtils.openMapByIos(this.currentLat, this.currentLong, this.currentAddress, this.currentMap)
				}
				this.cancleMap()
			},

			cancleMap() {
				this.topLoading = true
				this.showMap = false
				setTimeout(() => {
					this.topLoading = false
					this.currentLat = null
					this.currentLong = null
					this.currentAddress = null
					this.currentMap = null
				}, 500)
			},

			selectMap(type, phone) {
				this.currentMap = type
				this.currentMapPhone = phone
			},



		}
	}
</script>

<style lang='scss' scoped>
	.store-list {
		background-color: #f5f5f5;
		width: 100vw;
		color: #3D3A3A;

		image {
			image-rendering: -moz-crisp-edges;
			image-rendering: -o-crisp-edges;
			image-rendering: -webkit-optimize-contrast;
			image-rendering: crisp-edges;
			-ms-interpolation-mode: nearest-neighbor;
		}

		.bg-img {
			position: fixed;
			height: 100%;
			width: 100%;
			top: 0;
			left: 0;
		}

		.navbar-icon {
			font-weight: 500;
			font-size: 28rpx;
			display: flex;
			align-items: center;
			position: relative;
			padding-right: 36rpx;

			.icon-img {
				width: 28rpx;
				margin-right: 8rpx;
			}

			.arrow {
				border: 10rpx solid rgba(0, 0, 0, 0);
				border-top-color: #3D3A3A;
				margin-left: 14rpx;
				position: absolute;
				top: 16rpx;
				right: 0;
				transition: transform .5s;
				transform: rotate(0deg);
				transform-origin: 50% 25%;
			}

			.open {
				transform: rotate(180deg);
			}
		}

		.top-box {
			position: relative;

			.tabs-box {
				display: flex;
				height: 124rpx;
				align-items: center;
				justify-content: space-around;
				background-color: #f5f5f5;

				.tab-items {
					font-weight: 500;
					font-size: 30rpx;
					line-height: 44rpx;
					position: relative;
					padding-right: 36rpx;

					.arrow {
						border: 10rpx solid rgba(0, 0, 0, 0);
						border-top-color: #3D3A3A;
						position: absolute;
						top: 20rpx;
						right: 0;
						transition: transform .5s;
						transform: rotate(0deg);
						transform-origin: 50% 25%;
					}
				}

				.currnet {
					color: #EA5404;

					.arrow {
						border-top-color: #EA5404;
					}
				}

				.open {
					.arrow {
						transform: rotate(180deg);
					}
				}

				.color-open {
					.arrow {
						transform: rotate(180deg);
						border-top-color: #EA5404;
					}
				}
			}
		}

		.z-index {
			z-index: 10079;
		}

		.popups {
			width: 100vw;
			height: 100vh;
			background-color: rgba(0, 0, 0, 0.4);
			z-index: 10081;
			position: fixed;
			// top: 0rpx;
			left: 0;
		}

		.pop-con {
			width: 100%;
			background-color: #f5f5f5;
			font-size: 30rpx;
			line-height: 44rpx;

			.select-item {
				padding: 20rpx 0 20rpx;

				.item {
					text-align: center;
					padding-bottom: 48rpx;
				}

				.item:last-child {
					padding-bottom: 0rpx;
				}

				.selected {
					color: #EA5404;
				}
			}

			.select-item3 {
				display: flex;
				// justify-content: space-around;
				flex-wrap: wrap;

				.item {
					min-width: 33%;
				}
			}
		}

		.card-list {
			width: 100%;
			box-sizing: border-box;
			padding: 0 32rpx;

			.items {
				background-color: #fff;
				border-radius: 4rpx;
				display: flex;
				align-items: center;
				height: 336rpx;
				margin-bottom: 20rpx;

				.img-box {
					position: relative;
					height: 336rpx;

					.store-img {
						width: 240rpx;
						height: 336rpx;
						// display: inline-block;
					}

					.store-type {
						position: absolute;
						top: 0;
						left: 0;
						background: #EA5404;
						border-bottom-right-radius: 4rpx;
						font-size: 20rpx;
						line-height: 28rpx;
						color: #FFFFFF;
						padding: 8rpx 20rpx;
					}
				}

				.text-box {
					flex: 1;
					height: 100%;
					padding-left: 32rpx;
					// padding-right: 32rpx;
					position: relative;

					.store-name {
						font-weight: 600;
						font-size: 28rpx;
						line-height: 40rpx;
						padding-top: 20rpx;
					}

					.store-label {
						display: inline-block;
						font-size: 16rpx;
						line-height: 28rpx;
						color: #EA5404;
						padding: 4rpx 10rpx;
						border: 2rpx solid #EA5404;
						margin: 0rpx 8rpx 4rpx 0;
					}

					.store-address {
						font-size: 24rpx;
						line-height: 34rpx;
						color: #ADB0AE;
						padding-right: 32rpx;
						display: -webkit-box;
						overflow: hidden;
						text-overflow: ellipsis;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;

						image {
							width: 24rpx;
							margin-right: 12rpx;
						}
					}

					.store-km {
						padding-left: 32rpx;
					}

					.btn-box {
						width: calc(100% - 64rpx);
						display: flex;
						align-items: center;
						// justify-content: space-around;
						position: absolute;
						left: 32rpx;
						bottom: 20rpx;

						view {
							width: calc(50% - 12rpx);
							font-size: 26rpx;
							line-height: 38rpx;
							color: #FFFFFF;
							background: #EA5404;
							border-radius: 2px;
							padding: 8rpx 20rpx;

							image {
								width: 32rpx;
								height: 32rpx;
								vertical-align: top;
							}
						}

						.map-btn {
							margin-right: 24rpx;
						}
					}
				}
			}
		}

		// 地图
		.confirmdialog-content {
			width: 100%;

			.content-item {
				width: 100%;
				font-size: 32rpx;
				line-height: 108rpx;
				color: #828282;
				border-bottom: 1px solid #EDEDED;
				position: relative;
				display: flex;
				flex-direction: row;
				justify-content: space-between;

				.u-icon {
					position: absolute;
					right: 0;
					top: 34rpx;
				}
			}

			.content-item:last-child {
				border-bottom: none;
			}
		}
	}

	.end {
		text-align: center;
		color: #ADB0AE;
		line-height: 30px;
	}

	/deep/.u-slide-down-enter-active {
		position: absolute !important;
	}

	/deep/.u-popup .u-fade-enter-active {
		z-index: 10080 !important;
	}

	/deep/.u-popup .u-slide-up-enter-active {
		z-index: 10081 !important;
	}

	/deep/.u-popup .u-fade-zoom-enter-active {
		z-index: 10081 !important;
	}

	/deep/.u-modal__content {
		padding-bottom: 16rpx;
	}

	/deep/.u-modal__title {
		text-align: left;
		padding-left: 50rpx;
	}
</style>
